﻿using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using NLog;

namespace TfsGiggle.Core
{
    /// <summary>
    /// Provides the hosting code
    /// </summary>
    public sealed class WCFUtil : IDisposable
    {
        private ServiceHost _host;
        private ServiceHost _searchHost;
        private static Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// ctor
        /// </summary>
        public WCFUtil() { }

        /// <summary>
        /// Starts the listening
        /// </summary>
        /// <param name="port">Use this port number and port + 1</param>
        /// <returns>The addresses I'm listening on</returns>
        public Uri[] HostThisService(int port)
        {
            _logger.Trace("enter");
            try
            {
                Uri baseaddress = new Uri(string.Format("http://{0}:{1}", Environment.MachineName, port));
                _host = new ServiceHost(typeof(CheckinService), baseaddress);
                ServiceMetadataBehavior smb = _host.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null)
                {
                    smb = new ServiceMetadataBehavior();
                }
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Default;
                _host.Description.Behaviors.Add(smb);

                _host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
                var endPoint = _host.AddServiceEndpoint(typeof(ICheckinService), new WSHttpBinding(SecurityMode.None), "CheckinNotify");
                _host.Open();

                var searchAddress = new Uri(string.Format("http://{0}:{1}", Environment.MachineName, port + 1));
                _searchHost = new ServiceHost(typeof(Search), searchAddress);
                smb = _searchHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null)
                {
                    smb = new ServiceMetadataBehavior();
                }
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Default;
                _searchHost.Description.Behaviors.Add(smb);
                _searchHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
                var searchEndPoint = _searchHost.AddServiceEndpoint(typeof(ISearch), new WSHttpBinding(SecurityMode.None), "Search");
                _searchHost.Open();

                var addresses = new Uri[2];
                addresses[0] = endPoint.Address.Uri;
                addresses[1] = searchEndPoint.Address.Uri;
                _logger.Trace("Address1:{0} Address2:{1}", addresses[0], addresses[1]);
                return addresses;
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Exception caught", ex);
                throw;
            }
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_host != null)
                {
                    _host.Close();
                    _host = null;
                }
                if (_searchHost != null)
                {
                    _searchHost.Close();
                    _searchHost = null;
                }
            }
        }

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            _logger.Trace("enter");
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}